<template>
  <div class="checkout-container">
    <el-card shadow="hover" class="checkout-card">
      <!-- 商品列表 -->
      <h2 class="section-title">订单商品</h2>
      <el-table :data="cartItems" style="width: 100%">
        <el-table-column prop="name" label="商品名称" width="250" />
        <el-table-column label="单价" width="250">
          <template #default="scope">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="250" />
        <el-table-column label="小计">
          <template #default="scope">
        <span class="price-highlight">
          ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
        </span>
          </template>
        </el-table-column>
      </el-table>




      <!-- 收货地址 -->

      <!-- 收货地址 -->
      <h2 class="section-title">收货地址</h2>
      <el-radio-group v-model="selectedAddress" class="address-group" @change="handleAddressChange">
        <el-radio
            v-for="address in addresses"
            :key="address.id"
            :label="address.id"
            class="address-item"
            size="large"
        >
          <div class="address-info">
            <div class="address-header">
              <span class="receiver">{{ address.receiver }}</span>
              <span class="phone">{{ address.phone }}</span>
              <el-tag v-if="address.isDefault" size="small" type="danger">默认</el-tag>
              <!-- 地址操作按钮 -->
              <div class="address-actions">
                <el-button type="primary" link @click.stop="setDefaultAddress(address.id)">设置默认</el-button>
                <el-button type="primary" link @click.stop="editAddressItem(address)">编辑</el-button>
                <el-button type="danger" link @click.stop="deleteAddress(address.id)">删除</el-button>
              </div>
            </div>
            <div class="address-content">
              {{ address.province }} {{ address.city }} {{ address.district }} {{ address.detail }}
            </div>
          </div>
        </el-radio>
        <el-radio label="new" class="add-address">
          <el-icon><Plus /></el-icon> 添加新地址
        </el-radio>
      </el-radio-group>

      <!-- 编辑地址表单 -->
      <el-dialog
          v-model="editAddressForm"
          title="编辑地址"
          width="500px"
      >
        <el-form :model="editAddress" label-width="80px">
          <el-form-item label="收货人">
            <el-input v-model="editAddress.receiver" placeholder="请输入收货人姓名"/>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="editAddress.phone" placeholder="请输入手机号"/>
          </el-form-item>
          <!-- 替换编辑地址表单中的省市区输入框 -->
          <el-form-item label="所在地区">
            <el-cascader
                v-model="selectedEditRegion"
                :options="provinceCityData"
                :props="{
      value: 'value',
      label: 'label',
      children: 'children',
      expandTrigger: 'hover'
    }"
                placeholder="请选择省/市/区"    style="width: 100%"
                clearable
            />
          </el-form-item>
          <el-form-item label="详细地址">
            <el-input
                v-model="editAddress.detail"
                placeholder="请输入详细地址，如街道、门牌号等"
                type="textarea"
            />
          </el-form-item>
          <el-form-item label="设为默认">
            <el-switch v-model="editAddress.isDefault"/>
          </el-form-item>
        </el-form>
        <template #footer>
    <span class="dialog-footer">
      <el-button @click="cancelEditAddress">取消</el-button>
      <el-button type="primary" @click="updateAddress">确定</el-button>
    </span>
        </template>
      </el-dialog>




      <!-- 添加地址表单 -->
      <el-dialog
          v-model="showAddressForm"
          title="添加新地址"
          width="500px"
      >
        <el-form :model="newAddress" label-width="80px">
          <el-form-item label="收货人">
            <el-input v-model="newAddress.receiver" placeholder="请输入收货人姓名"/>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="newAddress.phone" placeholder="请输入手机号"/>
          </el-form-item>
          <!-- 替换添加地址表单中的省市区输入框 -->
          <el-form-item label="所在地区">
            <el-cascader
                v-model="selectedRegion"
                :options="provinceCityData"
                :props="{
      value: 'value',
      label: 'label',
      children: 'children',
      expandTrigger: 'hover'
    }"
                placeholder="请选择省/市/区"
                style="width: 100%"
                clearable
            />
          </el-form-item>
          <el-form-item label="详细地址">
            <el-input
                v-model="newAddress.detail"
                placeholder="请输入详细地址，如街道、门牌号等"
                type="textarea"
            />
          </el-form-item>

          <el-form-item label="设为默认">
            <el-switch v-model="newAddress.isDefault"/>
          </el-form-item>
        </el-form>
        <template #footer>
    <span class="dialog-footer">
      <el-button @click="cancelAddAddress">取消</el-button>
      <el-button type="primary" @click="submitNewAddress">确定</el-button>
    </span>
        </template>
      </el-dialog>

      <!-- 支付方式 -->
      <h2 class="section-title">支付方式</h2>
      <el-radio-group v-model="paymentMethod" class="payment-group">
        <el-radio label="alipay" class="payment-item">
          <el-icon><Wallet /></el-icon> 支付宝
        </el-radio>
        <el-radio label="wechat" class="payment-item">
          <el-icon><Money /></el-icon> 微信支付
        </el-radio>
        <el-radio label="bank" class="payment-item">
          <el-icon><CreditCard /></el-icon> 银行卡支付
        </el-radio>
      </el-radio-group>

      <!-- 订单总结 -->
      <div class="order-summary">
        <div class="summary-item">
          <span>商品总价:</span>
          <span>¥{{ subtotal.toFixed(2) }}</span>
        </div>
        <div class="summary-item">
          <span>运费:</span>
          <span>¥{{ 0 }}</span>
        </div>
        <!--        <div class="summary-item">-->
        <!--          <span>优惠:</span>-->
        <!--          <span class="discount-value">-¥{{ totalDiscount.toFixed(2) }}</span>-->
        <!--        </div>-->
        <div class="summary-item total-row">
          <span>应付总额:</span>
          <span class="total-price">¥{{ subtotal.toFixed(2) }}</span>
        </div>
      </div>

      <!-- 提交按钮 -->
      <div class="submit-section">
        <el-button
            type="primary"
            size="large"
            @click="submitOrder"
            :loading="submitting"
        >
          提交订单
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {ref, computed, onMounted, nextTick} from 'vue'
import {
  Plus,
  Wallet,
  Money,
  CreditCard
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from "axios";
import { regionData } from 'element-china-area-data'
import {useRoute} from "vue-router";
import router from "@/router/index.js";
// 添加响应式变量
const provinceCityData = ref(regionData)
const selectedRegion = ref([])  // 添加地址时使用
const selectedEditRegion = ref([])  // 编辑地址时使用
// 根据 code 查找地区信息的辅助函数
const findRegionByCode = (regions, code) => {
  for (const region of regions) {
    if (region.value === code) {
      return region
    }
    if (region.children) {
      const found = findRegionByCode(region.children, code)
      if (found) {
        return found
      }
    }
  }
  return null
}
// 添加获取完整订单的方法

// 商品数据（基于获取到的订单详情）
const cartItems = ref([])

// 简化版处理（假设products数组正确返回）
const fetchFullOrder = async (orderId) => {
  try {
    const response = await axios.get(`/api/order/ordertb/get-full/${orderId}`)
    const data = response.data

    const orderDetails = data.orderDetails || []
    const  products = data.products || []

    // 如果products数组为空，尝试单独获取
    if (products.length === 0) {
      const productPromises = orderDetails.map(detail =>
          axios.get(`/api/product/product/get?id=${detail.productId}`)
              .catch(() => ({ data: { id: detail.productId, name: '未知商品', price: 0 } }))
      )
      const productResponses = await Promise.all(productPromises)
      products.push(...productResponses.map(res => res.data))
    }

    // 将订单详情和商品信息合并成表格需要的格式
    cartItems.value = orderDetails.map(detail => {
      const product = products.find(p => p.id === detail.productId) || {}

      return {
        id: detail.productId,
        name: product.name || '商品名称',
        price: detail.priceAfter || product.priceAfter || 0, // 如果OrderDetails中有price字段
        quantity: detail.count // 使用count字段
      }
    })

    console.log('完整订单信息:', data)
    return data
  } catch (error) {
    console.error('获取完整订单失败:', error)
    ElMessage.error('获取订单信息失败')
  }
}



const selectedCoupon = ref(null)

// 积分数据
const userPoints = ref(1500)
const usedPoints = ref(0)
const showPoints = ref(false)
const maxUsablePoints = computed(() => Math.min(userPoints.value, 5000))

const setDefaultAddress = async (addressId) => {
  try {
    // 取消其他地址的默认状态
    await axios.put('/api/order/user-address/set-all-non-default', null, {
      params: { userId: userId.value }
    });

    // 设置当前地址为默认地址
    await axios.put(`/api/order/user-address/isdefault/${addressId}`);
    // 更新本地数据
    addresses.value = addresses.value.map(addr => ({
      ...addr,
      isDefault: addr.id === addressId
    }));

    // 更新选中地址
    selectedAddress.value = addressId;

    ElMessage.success('默认地址设置成功');
  } catch (error) {
    console.error('设置默认地址失败:', error);
    ElMessage.error('设置默认地址失败');
  }
}
// 地址编辑相关
const editAddressForm = ref(false)
const editAddress = ref({
  id: null,
  userId: 1001,
  receiver: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  isDefault: false
})
// 编辑地址的方法
const editAddressItem = (address) => {
  // 将选中的地址数据填充到编辑表单中
  editAddress.value = { ...address }
  // 根据地址的省市区信息查找对应的 code 值
  const province = provinceCityData.value.find(p => p.label === address.province)
  if (province) {
    const city = province.children.find(c => c.label === address.city)
    if (city) {
      const district = city.children.find(d => d.label === address.district)
      if (district) {
        selectedEditRegion.value = [province.value, city.value, district.value]
      } else {
        selectedEditRegion.value = [province.value, city.value]
      }
    } else {
      selectedEditRegion.value = [province.value]
    }
  }
  editAddressForm.value = true
}

// 更新地址的方法
const updateAddress = async () => {
  try { // 从级联选择器中提取省市区信息
    if (selectedEditRegion.value.length >= 3) {
      const provinceItem = findRegionByCode(provinceCityData.value, selectedEditRegion.value[0])
      const cityItem = findRegionByCode(provinceCityData.value, selectedEditRegion.value[1])
      const districtItem = findRegionByCode(provinceCityData.value, selectedEditRegion.value[2])

      editAddress.value.province = provinceItem?.label || ''
      editAddress.value.city = cityItem?.label || ''
      editAddress.value.district = districtItem?.label || ''
    } else if (selectedEditRegion.value.length > 0) {
      ElMessage.warning('请选择完整的省市区信息')
      return
    }

    // 验证必填字段
    if (!editAddress.value.receiver) {
      ElMessage.warning('请输入收货人姓名')
      return
    }
    if (!editAddress.value.phone) {
      ElMessage.warning('请输入手机号')
      return
    }
    if (!editAddress.value.province || !editAddress.value.city || !editAddress.value.district) {
      ElMessage.warning('请选择完整的省市区信息')
      return
    }
    if (!editAddress.value.detail) {
      ElMessage.warning('请输入详细地址')
      return
    }

    // 如果设置为默认地址，需要取消其他地址的默认状态
    if (editAddress.value.isDefault) {
      await axios.put('/api/order/user-address/set-all-non-default', null, {
        params: { userId: editAddress.value.userId }
      });

    }
    // 调用后端API更新地址
    const response = await axios.put('/api/order/user-address/update', editAddress.value)

    // 更新本地地址列表
    const index = addresses.value.findIndex(addr => addr.id === editAddress.value.id)
    if (index !== -1) {
      addresses.value[index] = { ...editAddress.value }
    }

    // 关闭编辑表单
    editAddressForm.value = false
    // 重新加载地址数据，确保界面与后端数据一致

    // 在 updateAddress 函数中修改这行
    await fetchAddresses({ value: editAddress.value.userId })
    ElMessage.success('地址更新成功！')
  } catch (error) {
    console.error('更新地址失败:', error)
    ElMessage.error('地址更新失败！')
  }
}
import { AuthService } from '@/service/auth.ts'
const authService = new AuthService()
const userId = ref(authService.getUserId())
// 取消编辑地址
const cancelEditAddress = () => {
  editAddressForm.value = false
  editAddress.value = {
    id: null,
    userId: userId.value,
    receiver: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    detail: '',
    isDefault: false
  }
}

// 删除地址的方法
const deleteAddress = async (addressId) => {
  try {
    // 调用后端API删除地址
    await axios.delete(`/api/order/user-address/delete?id=${addressId}`)

    // 从本地地址列表中移除
    addresses.value = addresses.value.filter(addr => addr.id !== addressId)

    // 如果删除的是当前选中的地址，则重新选择一个
    if (selectedAddress.value === addressId) {
      selectedAddress.value = addresses.value.length > 0 ? addresses.value[0].id : null
    }

    ElMessage.success('地址删除成功！')
  } catch (error) {
    console.error('删除地址失败:', error)
    ElMessage.error('地址删除失败！')
  }
}


// 添加新地址相关
const showAddressForm = ref(false)
const newAddress = ref({
  userId: 1001,
  receiver: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  isDefault: false
})

// 选择地址的处理方法
const handleAddressChange = (val) => {
  if (val === 'new') {
    // 显示新增地址表单
    showAddressForm.value = true
    // 重置选择地址为之前的值
    selectedAddress.value = addresses.value.length > 0 ? addresses.value[0].id : null
  } else {
    // 正常选择地址
    selectedAddress.value = val
  }
}

// 提交新地址
const submitNewAddress = async () => {
  try { // 从级联选择器中提取省市区信息
    if (selectedRegion.value.length >= 3) {
      // 根据 code 查找对应的 label
      const provinceItem = findRegionByCode(provinceCityData.value, selectedRegion.value[0])
      const cityItem = findRegionByCode(provinceCityData.value, selectedRegion.value[1])
      const districtItem = findRegionByCode(provinceCityData.value, selectedRegion.value[2])

      newAddress.value.province = provinceItem?.label || ''
      newAddress.value.city = cityItem?.label || ''
      newAddress.value.district = districtItem?.label || ''
    } else if (selectedRegion.value.length > 0) {
      ElMessage.warning('请选择完整的省市区信息')
      return
    }

    // 验证必填字段
    if (!newAddress.value.receiver) {
      ElMessage.warning('请输入收货人姓名')
      return
    }
    if (!newAddress.value.phone) {
      ElMessage.warning('请输入手机号')
      return
    }
    if (!newAddress.value.province || !newAddress.value.city || !newAddress.value.district) {
      ElMessage.warning('请选择完整的省市区信息')
      return
    }
    if (!newAddress.value.detail) {
      ElMessage.warning('请输入详细地址')
      return
    }


    // 如果设置为默认地址，需要取消其他地址的默认状态
    if (newAddress.value.isDefault) {
      await axios.put('/api/order/user-address/set-all-non-default', null, {
        params: { userId: editAddress.value.userId }});
    }
    // 这里应该调用后端API保存地址
    const response = await axios.post('/api/order/user-address/add', newAddress.value)

    // 模拟保存成功
    const newId = Date.now() // 实际应该使用后端返回的ID
    addresses.value.push({
      id: newId,
      ...newAddress.value
    })

    // 选择新添加的地址
    selectedAddress.value = newId
// 更新地址数据
    await fetchAddresses({ value: editAddress.value.userId })
    // 重置表单
    newAddress.value = {
      receiver: '',
      phone: '',
      province: '',
      city: '',
      district: '',
      detail: '',
      isDefault: false
    }

    // 隐藏表单
    showAddressForm.value = false

    ElMessage.success('地址添加成功！')
  } catch (error) {
    console.error('添加地址失败:', error)
    ElMessage.error('地址添加失败！')
  }
}

// 取消添加地址
const cancelAddAddress = () => {
  showAddressForm.value = false
  newAddress.value = {
    receiver: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    detail: '',
    isDefault: false
  }
}
// ... 其他 imports

// 地址数据
const addresses = ref([])
const selectedAddress = ref()

// 获取地址数据的方法
const fetchAddresses = async (userId) => {
  try {
    const response = await axios.get('/api/order/user-address/list-by-user', {
      params: {
        userId: userId.value  // 通过查询参数传递userId
      }
    })
    addresses.value = response.data

    // 自动选择默认地址
    const defaultAddress = response.data.find(addr => addr.isDefault)
    if (defaultAddress) {
      selectedAddress.value = defaultAddress.id
    } else if (response.data.length > 0) {
      // 如果没有默认地址，选择第一个地址
      selectedAddress.value = response.data[0].id
    }
  } catch (error) {
    console.error('获取地址数据失败:', error)
    // 可以添加错误提示逻辑
  }
}
// 确保 orderId 是响应式的
const route = useRoute()
const orderId = ref(route.query.orderId || route.params.orderId || 1)
// 在组件挂载时获取地址数据
onMounted(() => {
  fetchAddresses(userId)
  fetchFullOrder(orderId.value)
})

// 支付方式
const paymentMethod = ref('alipay')

// 订单状态
const submitting = ref(false)

// 计算属性
const subtotal = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
})

const shippingFee = computed(() => {
  return subtotal.value > 199 ? 0 : 15
})

const couponDiscount = computed(() => {
  if (!selectedCoupon.value) return 0
  const coupon = coupons.value.find(c => c.id === selectedCoupon.value)
  return coupon ? coupon.value : 0
})

const pointsDiscount = computed(() => {
  return usedPoints.value / 100
})

const totalDiscount = computed(() => {
  return couponDiscount.value + pointsDiscount.value
})

const totalAmount = computed(() => {
  return subtotal.value + shippingFee.value - totalDiscount.value
})
// 提交订单
const submitOrder = async () => {
  submitting.value = true

  // 创建要发送的数据对象
  const orderData = {
    id: orderId.value,
    payType: "0",
    addressId: selectedAddress.value
  }
  console.log(orderData)

  try {
    // 发送到后端更新接口
    const response = await axios.put('/api/order/ordertb/update', orderData)

    if (response.data) {
      ElMessage.success('订单更新成功！')
      // 可以添加路由跳转等逻辑
      await router.push(`/OrderView/${orderId.value}`)
    } else {
      ElMessage.error('订单更新失败！')
    }
  } catch (error) {
    console.error('订单提交失败:', error)
    ElMessage.error('订单提交失败！')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.checkout-container {
  max-width: 1800px;
  width: 1500px;
  margin: 20px auto;
  padding: 20px;
}

.checkout-card {
  padding: 30px;
}

.section-title {
  font-size: 18px;
  margin: 25px 0 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  color: #333;
}

.price-highlight {
  color: #ff5000;
  font-weight: bold;
}

.discount-section {
  margin-bottom: 20px;
}
.address-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 5px;
}

.address-text {
  flex: 1;
  color: #666;
  line-height: 1.5;
}

.address-actions {
  display: flex;
  gap: 10px;
  margin-left: 20px;
}

.address-actions .el-button {
  padding: 0;
}


.coupon-select {
  display: flex;
  align-items: center;
  gap: 20px;
}

.coupon-value {
  margin-left: 10px;
  color: #ff5000;
}

.points-section {
  margin-top: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.points-tip {
  color: #666;
  font-size: 14px;
}

.address-group {
  display: flex;
  flex-direction: column;
}

.address-item {
  margin-bottom: 15px;
  height: 50px;
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 35px;
  width: 100%;
}

.address-item.is-checked {
  border-color: #409eff;
}

.address-info {

  margin-left: 10px;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.receiver {
  font-weight: bold;
  margin-right: 15px;
}

.phone {
  margin-right: 15px;
  color: #666;
}

.address-detail {
  color: #666;
  line-height: 1.5;
}

.add-address {
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #dcdfe6;
  color: #606266;
}

.payment-group {
  display: flex;
  gap: 20px;
}

.payment-item {
  border: 1px solid #eee;
  padding: 15px 30px;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.payment-item.is-checked {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.order-summary {
  margin: 30px 0;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 4px;
  text-align: right;
}

.summary-item {
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
}

.discount-value {
  color: #ff5000;
}

.total-row {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #ddd;
  font-size: 16px;
}

.total-price {
  font-size: 22px;
  color: #ff5000;
  font-weight: bold;
}

.submit-section {
  text-align: center;
  margin-top: 20px;
}
.address-item ::v-deep(.el-radio__label) {
  width: 100%;
}

.address-info {
  width: 100%;
}

.address-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 5px;
}

.address-text {
  flex: 1;
  color: #666;
  line-height: 1.5;
  word-break: break-all;
}

.address-actions {
  display: flex;
  gap: 10px;
  flex-shrink: 0;
  margin-left: 20px;
}

.address-actions .el-button {
  padding: 0;
}
.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
  flex-wrap: wrap;
}

.receiver {
  font-weight: bold;
  margin-right: 15px;
}

.phone {
  margin-right: 15px;
  color: #666;
}

.address-actions {
  display: flex;
  gap: 10px;
  margin-left: auto; /* 将按钮推到右侧 */
}

.address-content {
  color: #666;
  line-height: 1.5;
  word-break: break-all;
  padding-left: 10px;
  border-left: 2px solid #eee;
  margin-left: 5px;
}

.address-item ::v-deep(.el-radio__label) {
  width: 100%;
  padding: 15px;
}

.address-item {
  margin-bottom: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
  width: 100%;
}

.address-item.is-checked {
  border-color: #409eff;
  background-color: #fafafa;
}

</style>